package com.demo;

import com.demo.bean.Config;
import com.demo.bean.Customer;
import com.demo.bean.Player;
import com.demo.bean.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        System.out.println("*************Start of Hello World!");

        //创建Spring ApplicationContext -- Spring上下文，即Spring容器
        //ClassPathXmlApplicationContext装载配置文件，来装配Bean
        //ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过Config类装配
        //ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        //通过扫描@Configuration配置类装配
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        //应用程序可以同时实例化多个SpringIoc容器
        ApplicationContext context2 = new ClassPathXmlApplicationContext("applicationContext.xml");
        //scan指定扫描包路径，包括子包，可以添加多个包作为参数
        //context.scan("com.demo.bean");

        System.out.println("--Context2：" + context2.getBean("customerBean"));

        //动态注册Bean，动态装配Bean不会初始化(实例化)Bean，因为InitializingBean、ApplicationContextAware等回调不会触发
        context.registerBean("playerBean", Player.class);
        context.registerBean("userBean", User.class);

        //扫描指定包之后，refresh()刷新Spring容器，重新装配扫描包后得到的Bean，refresh只能执行1次
        //context.refresh();

        Player player = (Player) context.getBean("playerBean");
        System.out.println(player);

//        User user = (User) context.getBean("userBean");
//        System.out.println(user);

        //通过Bean的名字name，通过context.getBean()获取对应Bean
        Customer customerBean = (Customer) context.getBean("customerBean");
        System.out.println(customerBean);
        customerBean.displayInfo();

        //调用close()，关闭Spring容器，删除所有Bean
        //((ClassPathXmlApplicationContext) context).close();
        ((AnnotationConfigApplicationContext) context).close();

        System.out.println("*************End of Hello World!");
    }
}
